from fastapi import Depends, FastAPI, HTTPException, Header
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from lisdemo.sql_app import crud
from lisdemo.sql_app.database import get_db
from lisdemo.mygeotools.trans import trans
import time
from lisdemo.routers import items, users

# models.Base.metadata.create_all(bind=engine)

app = FastAPI()


# Dependency 依赖项


# 新建用户
# @app.post("/users/", response_model=schemas.User)
# def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
#     db_user = crud.get_user_by_email(db, email=user.email)
#     if db_user:
#         raise HTTPException(status_code=400, detail="Email already registered")
#         # 电子邮件已注册
#     return crud.create_user(db=db, user=user)

# 读取用户（用户ID范围）
# @app.get("/users/")
# def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
#     users = crud.get_users(db, skip=skip, limit=limit)
#     return users

# # 用ID的方式读取用户

async def get_token_header(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


app.include_router(users.router,
                   prefix="/users",
                   tags=["users"],
                   responses={404: {"description": "Not found"}}
                   )
app.include_router(
    items.router,
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)



# 读取线

# 读取点
@app.get("/line/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_point = crud.get_point(db, user_id)
    for x in db_point:
        x.pointtime = time.mktime(x.pointtime.timetuple())
    allpoint = [i.to_geojson() for i in db_point]
    print(type(allpoint[0]))
    pan = trans.feature2gdf(allpoint)
    res = []
    user_id = pan['user_id'].unique()
    for index in user_id:
        point = pan[pan['user_id'] == index]['geometry'].apply(lambda x: list(x.coords[0]))
        path = point.values.tolist()
        # print(path)
        pointtime = pan[pan['user_id'] == index]['pointtime'].apply(float)
        # pointtime=pan[pan['user_id'] == index]['pointtime']
        timestamp = pointtime.values.tolist()
        # print(type(timestamp[0]))
        dict1 = {"vendor": int(index), "path": path, "timestamps": timestamp}
        res.append(dict1)
    if db_point is None:
        raise HTTPException(status_code=404, detail="User not found")
    return JSONResponse(res)


@app.get("/allline/")
def read_user(db: Session = Depends(get_db)):
    db_point = crud.getall_point(db)
    for x in db_point:
        x.pointtime = time.mktime(x.pointtime.timetuple())
    allpoint = [i.to_geojson() for i in db_point]
    pan = trans.feature2gdf(allpoint)
    res = []
    user_id = pan['user_id'].unique()
    for index in user_id:
        point = pan[pan['user_id'] == index]['geometry'].apply(lambda x: list(x.coords[0]))
        path = point.values.tolist()
        # print(path)
        pointtime = pan[pan['user_id'] == index]['pointtime'].apply(float)
        # pointtime=pan[pan['user_id'] == index]['pointtime']
        timestamp = pointtime.values.tolist()
        # print(type(timestamp[0]))
        dict1 = {"vendor": int(index), "path": path, "timestamps": timestamp}
        res.append(dict1)
    if db_point is None:
        raise HTTPException(status_code=404, detail="User not found")
    return JSONResponse(res)


# @app.get("/allusers/")
# def readall_user( db: Session = Depends(get_db)):
#     db_user = crud.getall_user(db)
#     alluser=[i.to_dict() for i in db_user]
#     if db_user is None:
#         raise HTTPException(status_code=404, detail="User not found")
#     return alluser
# # 设置用户拥有的项目（权限或作用域）
# @app.post("/users/{user_id}/items/", response_model=schemas.Item)
# def create_item_for_user(
#     user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
# ):
#     return crud.create_user_item(db=db, item=item, user_id=user_id)
#
# # 读取用户项目（权限或作用域）
# @app.get("/items/", response_model=List[schemas.Item])
# def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
#     items = crud.get_items(db, skip=skip, limit=limit)
#     return items


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=3333)
